<?php
class Login extends MY_Controller {

	public function __construct() {
		parent::MY_Controller();

		$this->load->helper(array('form','url', 'language'));
		$this->load->library('form_validation');

		$this->lang->load('login');
	}

	public function index() {
		if (!$this->input->post('action')) {
			$this->render('login/index');
		}
		else {
			try {
				if ($this->_submit_validate() === FALSE) {
					$data = array();
					$this->render('login/index', $data, $this->error(validation_errors('<li>','</li>')));
					return;
				}

				redirect('home/index/'.$this->input->post('id'));
			}
			catch (Exception $e) {
				echo '<pre>'; echo $e; echo '</pre>';
			}
		}
	}

	public function email() {
		if (!$this->input->post('action')) {
			$this->render('login/index');
		}
		else {
			try {
				if ($this->_submit_email_validate() === FALSE) {
					$data = array();
					$this->render('login/index', $data, $this->error(validation_errors('<li>','</li>')));
					return;
				}
				
				$id = Current_User::user()->id;

				redirect('home/index/'.$id);
			}
			catch (Exception $e) {
				echo '<pre>'; echo $e; echo '</pre>';
			}
		}
	}

	private function _submit_validate() {
		$this->_loadValidationMessages();

		// validation rules
		$this->form_validation->set_rules('id', 'lang:civl_id','required|numeric|min_length[3]|max_length[12]|callback_authenticate');
		$this->form_validation->set_rules('password', 'lang:password','required|min_length[3]|max_length[12]');

		return $this->form_validation->run();
	}

    private function _submit_email_validate() {
        $this->_loadValidationMessages();

        // validation rules
        $this->form_validation->set_rules('email', 'lang:email','required|email|callback_email_authenticate');
        $this->form_validation->set_rules('password', 'lang:password','required|min_length[3]|max_length[12]');

        return $this->form_validation->run();
    }

	public function authenticate() {
		return Current_User::login($this->input->post('id'), $this->input->post('password'));
	}

    public function email_authenticate() {
        return Current_User::loginByEmail($this->input->post('email'), $this->input->post('password'));
    }
}
